package com.tencent.qcloud.timchat.adapters

import android.view.View
import android.widget.ImageView
import android.widget.Toast

import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.chad.library.adapter.base.BaseQuickAdapter
import com.tencent.qcloud.timchat.ImInit
import com.tencent.qcloud.timchat.R
import com.tencent.qcloud.timchat.model.Conversation
import com.tencent.qcloud.timchat.model.ImChatUser
import com.tencent.qcloud.timchat.model.ImRequestListener
import com.tencent.qcloud.timchat.utils.TimeUtil

import q.rorbin.badgeview.Badge

/**
 * 会话界面adapter
 */
class ConversationRecyclerAdapter : BaseQuickAdapter<Conversation, ConversationViewHolder>(R.layout.item_conversation) {

    override fun convert(helper: ConversationViewHolder, item: Conversation) {
        helper.setText(R.id.name, item.name)
                .setText(R.id.last_message, item.lastMessageSummary)
                .setText(R.id.message_time, TimeUtil.getTimeStr(item.lastMessageTime))
        helper.badge.badgeNumber = item.unreadNum.toInt()
        helper.badge.setOnDragStateChangedListener { dragState, badge, targetView ->
            if (dragState == Badge.OnDragStateChangedListener.STATE_SUCCEED) {
                item.readAllMessage()
            }
        }
        Glide.with(mContext).load(item.avatar)
                .apply(RequestOptions().centerCrop().circleCrop().error(R.drawable.head_other).placeholder(R.drawable.head_other))
                .into(helper.getView<View>(R.id.avatar) as ImageView)
    }

    fun netNotifyDataSetChange() {
        val needRequestList = ArrayList<String>()
        for (item in data) {
            if (item.chatUser == null) {
                needRequestList.add(item.identify)
            }
        }
        if (needRequestList.isEmpty()) {
            notifyDataSetChanged()
        } else {
            ImInit.requestImChatUser(needRequestList, object : ImRequestListener() {
                override fun success(users: ArrayList<ImChatUser>?) {
                    users?.let {
                        for (item in data) {
                            for (user in users) {
                                if (item.identify == user.imUserName)
                                    item.chatUser = user
                            }
                        }
                    }
                    notifyDataSetChanged()
                }

                override fun error(result: Any?) {
                    notifyDataSetChanged()
                }
            })
        }
    }
}
